package cn.broadmax.boot.modules.sys.controller;


import cn.broadmax.boot.modules.sys.entity.SysFile;
import cn.broadmax.boot.base.SuperController;
import cn.broadmax.boot.config.AppBaseProperties;
import cn.broadmax.boot.exception.WebException;
import cn.broadmax.boot.log.SysLog;
import cn.broadmax.boot.modules.sys.service.ISysFileService;
import cn.broadmax.boot.util.SAssert;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import jexx.io.FileUtil;
import jexx.random.RandomUtil;
import jexx.time.DatePattern;
import jexx.time.DateUtil;
import jexx.util.StringUtil;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.File;
import java.io.InputStream;
import java.util.Date;
import java.util.Objects;

/**
 * <p>
 * 文件 前端控制器
 * </p>
 *
 * @author jexx
 * @since 2020-06-22
 */
@Api(tags = "文件")
@RestController
@RequestMapping("/sys/file")
@RequiredArgsConstructor
public class SysFileController extends SuperController {

    private final AppBaseProperties appBaseProperties;

    @Autowired
    private ISysFileService sysFileService;

    @ApiOperation(value = "上传单个文件(记录文件信息)")
    @SysLog(value = "上传文件")
    @PostMapping(value = "/upload" ,produces = MediaType.APPLICATION_JSON_VALUE, consumes = "multipart/form-data")
    public SysFile uploadFile(MultipartFile file){
        Objects.requireNonNull(file, "文件不能为空");

        String fileUrl = StringUtil.format("/{}/{}", DateUtil.format(new Date(), DatePattern.PURE_DATETIME_PATTERN),
                RandomUtil.simpleUUID());

        File f = FileUtil.file(appBaseProperties.getDataDir(), fileUrl);
        try(InputStream stream = file.getInputStream()){
            FileUtil.write(f, stream);
        }
        catch (Exception e){
            throw new WebException("上传失败");
        }

        SysFile sysFile = new SysFile();
        sysFile.setFileName(file.getOriginalFilename());
        sysFile.setFileSize(file.getSize());
        sysFile.setFileUrl(fileUrl);
        sysFileService.save(sysFile);
        return sysFile;
    }

    @ApiOperation(value = "根据ID下载文件")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "fileId", value = "文件ID", paramType="path", dataType = "string"),
            @ApiImplicitParam(name = "isDownload", value = "是否为下载模式", paramType="query", dataType = "boolean")
    })
    @GetMapping(value = "/{fileId}/download")
    public void downFile(@PathVariable String fileId, @RequestParam(defaultValue = "false") boolean isDownload,
                           HttpServletResponse response){
        SysFile sysFile = sysFileService.getById(fileId);
        SAssert.notNull(sysFile, "文件不存在");

        File file = FileUtil.file(appBaseProperties.getDataDir(), sysFile.getFileUrl());
        getFile(file, response, isDownload, sysFile.getFileName());
    }

}
